package sfeir.ergosum;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sfeir.ergosum.dao.DatabaseConnection;
import sfeir.ergosum.dao.DatabaseProvider;
import sfeir.ergosum.dao.RemoteProvider;
import sfeir.ergosum.emulator.AddContactQrActivity;
import sfeir.ergosum.menu.MenuService;
import sfeir.ergosum.tools.AnimationTools;
import sfeir.ergosum.tools.VCardParser;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.shaded.client.android.QRCaptureActivity;

public class AddContactActivity extends ListActivity {
    private static final int DIALOG_PROGRESS = 1;
    private static final int DIALOG_URL_ENTRY = 2;
    private static final int DIALOG_SPREADSHEET_ENTRY = 3;
    private static final int DIALOG_TEL_ENTRY = 4;
    private static final int DIALOG_ERGOSUM_ENTRY = 5;

    // For test only :
    private static final int REQUEST_QR_SDCARD = 0;

    /** Attribute key for the list item text. */
    private static final String LABEL = "LABEL";
    /** Attribute key for the list item icon's drawable resource. */
    private static final String ICON = "ICON";

    private ProgressDialog mProgressDialog;
    private Thread mThread;
    private String contactData;
    final Handler mHandler = new Handler();

    final Runnable invalidContact = new Runnable() {
        public void run() {
            Toast.makeText(AddContactActivity.this,
                    getString(R.string.contact_invalid), 3000).show();

        }
    };

    private int dialogBoxType;

    /**
     * Create the list with Add by SMS/Mail, Add by Qr and Add by URL
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // setTitle(R.string.main_menu_add);
        List<Map<String, Object>> menulist = buildList();
        SimpleAdapter adapter = new SimpleAdapter(
        // the Context
                this,
                // the data to display
                menulist,
                // The layout to use for each item
                R.layout.icon_list_item,
                // The list item attributes to display
                new String[] { LABEL, ICON },
                // And the ids of the views where they should be displayed (same
                // order)
                new int[] { android.R.id.text1, android.R.id.icon });

        setListAdapter(adapter);
        setTheme(R.style.ListTheme);
        setContentView(R.layout.list);

        // Use an existing ListAdapter that will map an array
        // of strings to TextViews
        // String[] mStrings = {
        // // "Ajouter par SMS/Mail", "Ajouter par code bare",
        // // "Ajouter URL"
        // getString(R.string.add_contact_list_add_sms_mail),
        // getString(R.string.add_contact_list_add_qr),
        // getString(R.string.add_contact_list_add_url)
        // /*getString(R.string.add_contact_list_add_spreadsheet)*/ };
        // setListAdapter(new ArrayAdapter<String>(this,
        // android.R.layout.simple_list_item_1, mStrings));
        // //getListView().setTextFilterEnabled(true);

        AnimationTools.setAnimation(getListView());
    }

    /**
     * Build the list of item in this list menu
     * 
     * @return a list of map which contain the LABEL and ICON field
     */
    private List<Map<String, Object>> buildList() {
        // Resulting list...
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(5);

        // Add contact by SMS
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put(LABEL, getString(R.string.add_contact_list_add_sms_mail));
        map1.put(ICON, R.drawable.share_sms);
        list.add(map1);
        // Add by a QR code bar
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put(LABEL, getString(R.string.add_contact_list_add_qr));
        map2.put(ICON, R.drawable.qrcode);
        list.add(map2);
        // Add by an .Tel
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put(LABEL, getString(R.string.add_contact_list_add_tel));
        map3.put(ICON, R.drawable.dottel);
        list.add(map3);
        // Add by ErgoSum
        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put(LABEL, getString(R.string.add_contact_list_add_ergosum));
        map4.put(ICON, R.drawable.ergosum);
        list.add(map4);
        // Add by Url
        Map<String, Object> map5 = new HashMap<String, Object>();
        map5.put(LABEL, getString(R.string.add_contact_list_add_url));
        map5.put(ICON, R.drawable.web);
        list.add(map5);
        return list;
    }

    /**
     * Create the dialog
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_PROGRESS:
            mProgressDialog = new ProgressDialog(AddContactActivity.this);
            mProgressDialog.setTitle(R.string.add_contact_wait_url);
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setButton2(getText(R.string.dialog_cancel),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {

                            mThread.stop();
                            mProgressDialog.dismiss();
                            /* User clicked No so do some stuff */
                        }
                    });
            return mProgressDialog;
        case DIALOG_SPREADSHEET_ENTRY:
            return getDialog(DIALOG_SPREADSHEET_ENTRY);
        case DIALOG_URL_ENTRY:
            return getDialog(DIALOG_TEL_ENTRY);
        case DIALOG_TEL_ENTRY:
            return getDialog(DIALOG_TEL_ENTRY);
        case DIALOG_ERGOSUM_ENTRY:
            return getDialog(DIALOG_ERGOSUM_ENTRY);
        }
        return null;
    }

    private Dialog getDialog(int dialogType) {
        dialogBoxType = dialogType;
        // This example shows how to add a custom layout to an AlertDialog
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.input_text_dialog,
                null);
        final TextView textInstruction = (TextView) textEntryView
                .findViewById(R.id.instruction_dialog);
        final EditText urlET = (EditText) textEntryView
                .findViewById(R.id.input_dialog);

        textInstruction
                .setText((dialogBoxType == DIALOG_SPREADSHEET_ENTRY) ? R.string.spreadsheet_dialog_text
                        : R.string.url_dialog_text);

        return new AlertDialog.Builder(AddContactActivity.this)
                // .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(
                        (dialogBoxType == DIALOG_SPREADSHEET_ENTRY) ? R.string.add_contact_list_add_spreadsheet
                                : R.string.add_contact_list_add_url)
                .setView(textEntryView).setPositiveButton(R.string.dialog_ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                showDialog(DIALOG_PROGRESS);
                                /* User clicked OK so do some stuff */
                                mThread = new Thread() {
                                    public void run() {
                                        RemoteProvider dao = new RemoteProvider(
                                                new DatabaseConnection(
                                                        AddContactActivity.this));

                                        if (dialogBoxType == DIALOG_SPREADSHEET_ENTRY) {
                                            if (dao.addContactBySpreadsheet(
                                                    urlET.getText().toString(),
                                                    "") == null)
                                                mHandler.post(invalidContact);
                                            else
                                                AddContactActivity.this
                                                        .setResult(RESULT_OK);
                                        } else if (dialogBoxType == DIALOG_ERGOSUM_ENTRY) {
                                            if (dao.addContactByErgoSum(urlET
                                                    .getText().toString()) == null)
                                                mHandler.post(invalidContact);
                                            else
                                                AddContactActivity.this
                                                        .setResult(RESULT_OK);
                                        } else if (dialogBoxType == DIALOG_TEL_ENTRY)
                                            if (dao.addContactByWebsite(urlET
                                                    .getText().toString()) == null)
                                                mHandler.post(invalidContact);
                                            else
                                                AddContactActivity.this
                                                        .setResult(RESULT_OK);
                                        mProgressDialog.dismiss();
                                    }
                                };
                                mThread.start();
                            }
                        }).setNegativeButton(R.string.dialog_cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                /* User clicked cancel so do some stuff */
                            }
                        }).create();
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        if (DIALOG_PROGRESS != id) {
            ((EditText) dialog.findViewById(R.id.input_dialog))
                    .setText(contactData);
        }
        /*} else if (DIALOG_SPREADSHEET_ENTRY == id) {
            ((EditText) dialog.findViewById(R.id.input_dialog))
                    .setText(contactData);
        }*/
    }

    /**
     * Lauch the activity on clic on the list
     * 
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        switch (position) {
        case 0: // Add by SMS/Mail
            // Toast.makeText(this, "Ajouter par SMS/Mail", 2000).show();
            startActivityForResult(new Intent(AddContactActivity.this,
                    AddContactSMSMailActivity.class), MenuService.REFRESH);
            break;
        case 1: // Add by Qr
            // Toast.makeText(this, "Ajouter par code barre", 2000).show();
            if (0 == ((SensorManager) getSystemService(SENSOR_SERVICE))
                    .getSensors())
                startActivityForResult(new Intent(AddContactActivity.this,
                        AddContactQrActivity.class), REQUEST_QR_SDCARD);
            else {
                Intent intent = new Intent(this, QRCaptureActivity.class);
                intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                startActivityForResult(intent, REQUEST_QR_SDCARD);
            }
            break;
        case 2: // Add by Tel
            // Toast.makeText(this, "Ajouter par url", 2000).show();
            // startActivity(new Intent(AddContactActivity.this,
            // AddContactURLActivity.class));
            showDialog(DIALOG_TEL_ENTRY);
            break;
        case 3: // Add by ErgoSum
            // Toast.makeText(this, "Ajouter par url", 2000).show();
            // startActivity(new Intent(AddContactActivity.this,
            // AddContactURLActivity.class));
            showDialog(DIALOG_ERGOSUM_ENTRY);
            break;
        case 4: // Add by Url
            // Toast.makeText(this, "Ajouter par url", 2000).show();
            // startActivity(new Intent(AddContactActivity.this,
            // AddContactURLActivity.class));
            showDialog(DIALOG_URL_ENTRY);
            break;
        /*
         * case 3: // Add by spreadsheet key
         * showDialog(DIALOG_SPREADSHEET_ENTRY); break;
         */
        default:
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (REQUEST_QR_SDCARD == requestCode) {
            if (RESULT_OK == resultCode) {
                this.contactData = data.getStringExtra("SCAN_RESULT");

                if (contactData.startsWith("BEGIN:VCARD")) {
                    mThread = new Thread() {
                        public void run() {
                            DatabaseProvider dp = new DatabaseProvider(
                                    new DatabaseConnection(
                                            AddContactActivity.this));
                            dp.open();
                            if (null == dp.addContact(VCardParser
                                    .parse(contactData)))
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                            dp.close();
                            mProgressDialog.dismiss();

                        }
                    };
                    mThread.start();
                } else {
                    // if (contactData.toLowerCase().contains("http://")
                    // || contactData.toLowerCase().contains("www.") ||
                    // contactData.matches("\\."))
                    if (contactData.matches("(\\w|-)+"))
                        showDialog(DIALOG_SPREADSHEET_ENTRY);
                    else
                        showDialog(DIALOG_URL_ENTRY);
                }

            } else {
                Toast.makeText(this, "Scan cancelled", 1000).show();
            }
        }

        if (requestCode == MenuService.REFRESH) {
            if (RESULT_OK == resultCode) {
                setResult(RESULT_OK);
            }
        }
    }

    // Lauch with an URL (ergo://) or with a vcard file
    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();

        final String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            final Uri url = intent.getData();
            if (url != null) {
                Log.e("ErgoSum", "ErgoSum open URL : " + url.toString());
                showDialog(DIALOG_PROGRESS);
                /* User clicked OK so do some stuff */
                mThread = new Thread() {
                    public void run() {
                        String type = url.getHost();
                        RemoteProvider dao = new RemoteProvider(
                                new DatabaseConnection(AddContactActivity.this));
                        if (type.contains("spreadsheets.google.com")) {
                            String key = url.getQueryParameter("key");
                            String alias = url.getFragment();
                            if (alias == null)
                                alias = "";
                            if (key != null)
                                if (dao.addContactBySpreadsheet(key, alias) == null)
                                    mHandler.post(invalidContact);
                                else
                                    AddContactActivity.this
                                            .setResult(RESULT_OK);
                        } else if (url.getScheme().equals("file")) {
                            if (dao.addContactByFile(url) == null)
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                        } else if (url.getAuthority().equals("ergosum")) {
                            if (dao.addContactByErgoSum(url.getLastPathSegment()) == null)
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                        } else {
                            String u = "http:" + url.getSchemeSpecificPart();
                            if (dao.addContactByWebsite(u) == null)
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                        }

                        mProgressDialog.dismiss();

                    }
                };
                mThread.start();

            }
        }
    }
}
